/**
 * This file is part of gapro library.
 * 
 * gapro library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>
 * 
 * Copyright 2012 Vinay Penmatsa. All rights reserved.
 * 
 */
package org.stupidwhiz.gapro.core;

/**
 * Represents a fraction with numerator and denominator
 * 
 * @author Vinay Penmatsa
 * @since 1.0
 */
public class Fraction implements Comparable<Fraction>, Cloneable {
    private int numerator;
    private int denominator;

    /**
     * Creates Fraction with given numerator and denominator
     * 
     * @param numerator
     *            the numerator
     * @param denominator
     *            the denominator
     */
    public Fraction(int numerator, int denominator) {
        if(denominator == 0)
            throw new IllegalArgumentException("Denominator cannot be zero");
        this.numerator = numerator;
        this.denominator = denominator;
        reduce();
    }

    /**
     * Creates Fraction with given string form "m/n" or "m", n != 0
     * 
     * @param fraction
     *            a string form of fraction
     */
    public Fraction(String fraction) {
        if(!Util.hasValue(fraction))
            throw new IllegalArgumentException("Invalid fraction string format. Should be \"m\" or \"m/n\"");
        fraction = fraction.trim();
        try {
            if(fraction.contains("/")) {
                String[] sp = fraction.split("/");
                numerator = Integer.parseInt(sp[0].trim());
                denominator = Integer.parseInt(sp[1].trim());
                if(denominator == 0)
                    throw new IllegalArgumentException("Denominator cannot be zero");
            } else {
                numerator = Integer.parseInt(fraction);
                denominator = 1;
            }
        } catch(Exception e) {
            throw new IllegalArgumentException("Invalid fraction string format. Should be \"m\" or \"m/n\"");
        }
        reduce();
    }

    /**
     * Creates a fraction from given numerator and denominator
     * 
     * 
     * @param numerator
     *            the numerator
     * @param denominator
     *            the denominator
     */
    public static final Fraction createFraction(int numerator, int denominator) {
        return new Fraction(numerator, denominator);
    }

    /**
     * Creates a fraction from the string representation "m/n" "m" will be considered as "m/1"
     * 
     * 
     * @param s
     */
    public static final Fraction createFraction(String s) {
        return new Fraction(s);
    }

    /**
     * Creates Fraction from given integer. Denominator will be 1.
     * 
     * @param numerator
     *            the numerator
     */
    public Fraction(int numerator) {
        this(numerator, 1);
    }

    /**
     * Returns the numerator of the fraction
     * 
     * @return the numerator
     */
    public int getNumerator() {
        return numerator;
    }

    /**
     * Sets the numerator
     * 
     * @param numerator
     *            the numerator
     */
    public void setNumerator(int numerator) {
        this.numerator = numerator;
        reduce();
    }

    /**
     * Returns the denominator of the fraction
     * 
     * @return the denominator
     */
    public int getDenominator() {
        return denominator;
    }

    /**
     * Sets the denominator
     * 
     * @param denominator
     *            the denominator of the fraction
     * @throws IllegalArgumentException
     *             when denominator is zero
     */
    public void setDenominator(int denominator) {
        if(denominator == 0)
            throw new IllegalArgumentException("Denominator cannot be zero");
        this.denominator = denominator;
        reduce();
    }

    /**
     * Negates the sign
     * 
     * @return the resulting fraction
     */
    public Fraction negate() {
        numerator = -numerator;
        return this;
    }

    /**
     * Adds another fraction to this fraction
     * 
     * @param fraction
     *            the fraction to add
     */
    public Fraction add(final Fraction fraction) {
        numerator = numerator * fraction.denominator + denominator * fraction.numerator;
        denominator = denominator * fraction.denominator;
        reduce();

        return this;
    }

    /**
     * Subtract another fraction from this fraction
     * 
     * @param fraction
     *            the fraction to add
     */
    public Fraction subtract(final Fraction fraction) {
        numerator = numerator * fraction.denominator - denominator * fraction.numerator;
        denominator = denominator * fraction.denominator;
        reduce();

        return this;
    }

    /**
     * Multiply this fraction with given fraction
     * 
     * @param fraction
     *            the fraction to multiply
     */
    public Fraction multiply(final Fraction fraction) {
        numerator = numerator * fraction.numerator;
        denominator = denominator * fraction.denominator;
        reduce();

        return this;
    }

    /**
     * Divide this fraction with given fraction
     * 
     * @param fraction
     *            the fraction to multiply
     */
    public void divide(Fraction fraction) {
        if(fraction.numerator == 0) {
            throw new IllegalArgumentException("Cannot divide with zero");
        }
        numerator = numerator * fraction.denominator;
        denominator = denominator * fraction.numerator;
        reduce();
    }

    /**
     * Inverses the fraction
     */
    public void inverse() {
        if(numerator == 0)
            throw new IllegalStateException("Fraction with numerator 0 cannot be inversed");
        int t = denominator;
        denominator = numerator;
        numerator = t;
    }

    /**
     * Reduces the fraction.
     * 
     */
    public void reduce() {
        if(numerator <= 0 && denominator < 0) {
            numerator = Math.abs(numerator);
            denominator = Math.abs(denominator);
        }
        if(denominator < 0) {
            numerator = -numerator;
            denominator = -denominator;
        }

        int gcd = Math.abs(Util.gcd(numerator, denominator));
        numerator = numerator / gcd;
        denominator = denominator / gcd;
    }

    /**
     * Returns '+' or '-'
     * 
     * @return
     */
    public char sign() {
        if(numerator >= 0 && denominator > 0)
            return '+';
        return '-';
    }

    /**
     * Returns the double value of the fraction
     * 
     * @return the computed value
     */
    public double toDouble() {
        return (1.0d * numerator) / denominator;
    }

    @Override
    public String toString() {
        return numerator + (denominator == 1 ? "" : "/" + denominator);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + denominator;
        result = prime * result + numerator;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj)
            return true;
        if(obj == null)
            return false;
        if(getClass() != obj.getClass())
            return false;
        Fraction other = (Fraction) obj;

        if(denominator != other.denominator)
            return false;
        if(numerator != other.numerator)
            return false;
        return true;
    }

    @Override
    public int compareTo(Fraction f) {
        int lcm = Util.lcm(denominator, f.denominator);
        int mult1 = lcm / denominator;
        Fraction f1 = new Fraction(numerator * mult1, lcm);
        int mult2 = lcm / f.denominator;
        Fraction f2 = new Fraction(numerator * mult2, lcm);

        return f1.numerator - f2.numerator;
    }

    /**
     * Compares with the absolute values disregarding the sign
     * 
     * @param f
     * @return
     */
    public int compareToAbs(Fraction f) {
        int lcm = Util.lcm(denominator, f.denominator);
        int mult1 = lcm / denominator;
        Fraction f1 = new Fraction(numerator * mult1, lcm);
        int mult2 = lcm / f.denominator;
        Fraction f2 = new Fraction(f.numerator * mult2, lcm);

        return Math.abs(f1.numerator) - Math.abs(f2.numerator);
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}
